/*
 * RGBMap.cpp
 *
 *  Created on: Oct 10, 2012
 *      Author: burek
 */


#include <cstdlib>
#include <cstring>
#include <cstdio>

#include "RGBMap.h"
#include "math/util.h"

//#define _DEBUG

RGBMap::RGBMap(Uint32 Width, Uint32 Height)
{
	width = Width;
	height = Height;
	data = new Vec3D[width * height];
}

RGBMap::~RGBMap()
{
	delete[] data;
}

void RGBMap::pset(Uint32 x, Uint32 y, Vec3D texel)
{
#ifdef _DEBUG
	if(x >= 0 && y >= 0 && x < width && y < height) {
#endif
		data[x + y * width] = texel;
#ifdef _DEBUG
	}
#endif
}

void RGBMap::pset(Uint32 x, Uint32 y, float R, float G, float B)
{
#ifdef _DEBUG
	if(x >= 0 && y >= 0 && x < width && y < height) {
#endif
		data[x + y * width].set(R, G, B);
#ifdef _DEBUG
	}
#endif
}

Vec3D RGBMap::pget(Uint32 x, Uint32 y) const
{
#ifdef _DEBUG
	if(x >= 0 && y >= 0 && x < width && y < height) {
#endif
		return data[x + y * width];
#ifdef _DEBUG
	}
	else
	{
		return Vec3D::Zero;
	}
#endif
}

Vec3D RGBMap::sample(float x, float y) const
{
	Uint32 X = (Uint32)x;
	Uint32 Y = (Uint32)y;
	Uint32 X1 = X % width;
	Uint32 Y1 = Y % height;
	Uint32 X2 = (X + 1) % width;
	Uint32 Y2 = (Y + 1) % height;
	float u = x - (int)X;
	float v = y - (int)Y;
	return LERP(LERP(data[X1 + Y1 * width], data[X2 + Y1 * width], u),
			LERP(data[X1 + Y2 * width], data[X2 + Y2 * width], u), v);
}

void RGBMap::clear()
{
	memset(data, 0, width * height * sizeof(Vec3D));
}


